<template>
  <div id="login">
    <div class="form-wrap">
      <div class="form-container">
        <h1 class="system-title">求职招聘系统</h1>
        <ul class="menu-tab">
          <li :class="{ current: current_menu === item.type }" v-for="item in tab_menu" :key="item.type"
            @click="toggleMenu(item.type)">
            {{ item.label }}
          </li>
        </ul>
        <div>
          <el-form ref="formRef" :model="form" :rules="form_rules" status-icon>
            <el-form-item prop="username">
              <label class="form-label">用户名</label>
              <el-input v-model="form.username" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item prop="password">
              <label class="form-label">密码</label>
              <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
            <el-form-item v-if="current_menu === 'register'" prop="email">
              <label class="form-label">邮箱</label>
              <el-input v-model="form.email" placeholder="请输入邮箱" clearable />
            </el-form-item>
            <el-form-item v-if="current_menu === 'register'" prop="role">
              <label class="form-label">注册类型</label>
              <el-select v-model="form.role" placeholder="请选择注册类型" style="width: 100%">
                <el-option label="普通用户" value="user" />
                <el-option label="企业用户" value="enterprise" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="current_menu === 'register'">
              <label class="form-label">头像（可选）</label>
              <el-upload
                class="avatar-uploader"
                :auto-upload="false"
                :on-change="handleAvatarChange"
                :show-file-list="false"
                accept="image/*">
                <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button :type="submit_button_disabled ? 'info' : 'danger'" class="el-button-block"
                :disabled="submit_button_disabled" :loading="submit_button_loading" @click="handleSubmit">
                {{ current_menu === 'login' ? '登录' : '注册' }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <starry-sky :stars-count="1000" :distance="1000" />
    </div>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { validateEmail, validatePassword } from '@/utils/validate'
import useStore from '@/store'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()

const avatarPreview = ref('')
const avatarFile = ref(null)

const validate_name_rules = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else {
    callback()
  }
}

const validate_password_rules = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (!validatePassword(value)) {
    callback(new Error('请输入6-20位密码，包含数字和字母'))
  } else {
    callback()
  }
}

const validate_email_rules = (rule, value, callback) => {
  if (data.current_menu === 'login') {
    callback()
  }
  if (value === '') {
    callback(new Error('请输入邮箱'))
  } else if (!validateEmail(value)) {
    callback(new Error('邮箱格式不正确'))
  } else {
    callback()
  }
}

const data = reactive({
  tab_menu: [
    { type: 'login', label: '登录' },
    { type: 'register', label: '注册' },
  ],
  current_menu: 'login',
  form: {
    username: '',
    password: '',
    email: '',
    role: 'user'
  },
  form_rules: {
    username: [
      { required: true, validator: validate_name_rules, trigger: 'change' },
    ],
    password: [
      { required: true, validator: validate_password_rules, trigger: 'change' },
    ],
    email: [
      { required: true, validator: validate_email_rules, trigger: 'change' },
    ],
  },
  submit_button_disabled: false,
  submit_button_loading: false,
})

const formRef = ref(null)
let { tab_menu, current_menu, form, form_rules, submit_button_disabled, submit_button_loading } = toRefs(data)

const toggleMenu = (type) => {
  current_menu.value = type
  formRef.value.clearValidate()
  submit_button_disabled.value = false
}

const handleAvatarChange = (file) => {
  avatarFile.value = file.raw
  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const reset = () => {
  //重置表单
  formRef.value.resetFields()
  avatarPreview.value = ''
  avatarFile.value = null
  form.value.role = 'user'
  // 切换到登录模式
  current_menu.value = 'login'
  // 禁用登录按钮
  submit_button_disabled.value = false
  // 取消提交按钮的加载状态
  submit_button_loading.value = false
};

const register = async () => {
  const { username, password, email, role } = form.value

  // 使用FormData支持文件上传
  const formData = new FormData()
  formData.append('username', username)
  formData.append('password', password)
  formData.append('email', email)
  formData.append('role', role)
  
  // 如果有头像，添加到formData
  if (avatarFile.value) {
    formData.append('avatar', avatarFile.value)
  }

  submit_button_loading.value = true
  try {
    const res = await store.app.registerAction(formData)
    ElMessage.success(res.msg)
    // 注册成功后自动切换到登录
    reset()
    current_menu.value = 'login'
  } catch (error) {
    submit_button_loading.value = false
  }
}

const login = async () => {
  const { username, password } = form.value

  const requestData = {
    username,
    password
  }

  submit_button_loading.value = true
  try {
    const res = await store.app.loginAction(requestData)
    ElMessage.success(res.msg)
    
    // 根据用户角色跳转到不同页面
    const userRole = res.data?.role || store.app.role
    const enterpriseId = res.data?.enterpriseId || store.app.enterpriseId
    let targetRoute = '/'
    
    if (userRole === 'user') {
      // 普通用户跳转到用户主页
      targetRoute = '/'
    } else if (userRole === 'enterprise') {
      // 企业员工：检查是否有对应的企业ID
      if (enterpriseId) {
        // 跳转到该企业的管理首页
        targetRoute = `/frontend/enterprise-home?enterpriseId=${enterpriseId}`
      } else {
        // 如果没有企业ID，说明该用户不是员工或员工已离职
        ElMessage.error('您的账号未关联到任何企业，请联系管理员')
        submit_button_loading.value = false
        return
      }
    } else if (userRole === 'admin') {
      // 管理员跳转到管理后台
      targetRoute = '/backend'
    }
    
    router.push(targetRoute)
  } catch (error) {
    console.log('error', error);
    submit_button_loading.value = false
  }
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    console.log('valid', valid);
    if (valid) {
      current_menu.value == 'login' ? login() : register();
    }
  })
}

onBeforeUnmount(() => {
  // 清理工作
})
</script>

<style scoped src="@/assets/style/user/login.css"></style>